<template>
  <div class="app-container">
    <div
      class="box"
      v-if="['发起', '草稿', '审批', '查看'].includes(templateType)"
    >
      <div
        class="box"
        style="display: flex; justify-content: end;"
        v-if="!['发起'].includes(templateType)"
      >
        <el-button
          type="info"
          size="mini"
          v-if="options.enabledAbort"
          @click="submitFormOption('ABORT')"
        >
          作废
        </el-button>
        <el-button
          type="danger"
          size="mini"
          v-if="options.enabledWithdraw"
          @click="submitFormOption('WITHDRAW')"
        >
          撤销
        </el-button>
        <el-button
          type="danger"
          size="mini"
          v-if="options.enabledDelete"
          @click="submitFormOption('DELETE')"
        >
          删除
        </el-button>
      </div>

      <div
        class="box"
        v-if="['草稿', '审批', '查看'].includes(templateType)"
      >
        <el-descriptions
          :column="3"
          border
        >
          <el-descriptions-item label="流程单号">
            {{ paramsData.flowNo }}
          </el-descriptions-item>
          <el-descriptions-item label="标题">
            {{ paramsData.flowName }}
          </el-descriptions-item>
          <el-descriptions-item label="流程分类">
            {{ paramsData.templateName }}
          </el-descriptions-item>
          <el-descriptions-item label="业务发起人">
            {{ paramsData.creatorNickName }}
          </el-descriptions-item>
          <el-descriptions-item label="发起时间">
            {{ paramsData.createTime }}
          </el-descriptions-item>
        </el-descriptions>
      </div>
      <!-- options.enabledEditDoc -->
      <component
        :disabled="['审批', '查看'].includes(templateType)"
        :doc="doc"
        :flowInfo="flowInfo"
        :templateType="templateType"
        :flowNo="paramsData.flowNo"
        :templateName="templateName"
        :templateId="templateId"
        :is="currentFormComponent"
        :options="options"
        @submit="handleFormSubmit"
        ref="component"
      ></component>
    </div>

    <div v-if="templateType == '审批'">
      <div
        class="box"
        v-if="options.enabledToNext"
      >
        <el-card class="box-card">
          <div class="title">
            审核
          </div>
          <el-form
            :model="ruleForm"
            :rules="rules"
            ref="ruleForm"
            label-width="150px"
            class="demo-ruleForm"
          >
            <el-form-item
              label="审批意见"
              prop="approvalMsg"
              v-if="options.enabledSubmitMsg"
            >
              <el-input
                type="textarea"
                v-model="ruleForm.approvalMsg"
                placeholder="请输入审批意见"
              ></el-input>
            </el-form-item>

            <el-form-item
              label="审批处理"
              prop="action"
            >
              <el-radio-group v-model="ruleForm.action">
                <el-radio label="TO_NEXT">通过</el-radio>
                <el-radio
                  label="TO_PRIV"
                  v-if="options.enabledToPriv"
                >驳回</el-radio>
                <el-radio
                  label="TO_FIRST"
                  v-if="options.enabledToFirst"
                >驳回到起点</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item
              label="下一节点审批人"
              prop="targetUserName"
              v-if="!lastNode && ruleForm.action == 'TO_NEXT'"
            >
              <el-radio-group v-model="ruleForm.targetUserName">
                <el-radio
                  :label="item.userName"
                  v-for="item in approveList"
                  :key="item.userName"
                >{{ item.nickName }}</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item>
              <el-button
                type="primary"
                @click="submitForm('ruleForm')"
              >提交</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </div>
    <div v-if="['草稿', '审批', '查看'].includes(templateType)">
      <div class="box">
        <el-card class="box-card">
          <div class="title">
            审批历史记录
          </div>
          <el-table
            :data="flowLogList"
            style="width: 100%;"
            border
            height="200"
          >
            <el-table-column
              prop="submitUserNickName"
              label="发起人"
              :show-overflow-tooltip="true"
              width="200px"
            >
            </el-table-column>
            <el-table-column
              prop="submitTime"
              label="发起时间"
              width="200px"
            >
            </el-table-column>
            <el-table-column
              prop="submitOperationName"
              label="审核结果"
              width="150px"
            >
            </el-table-column>
            <el-table-column
              prop="customSummary"
              label="摘要"
              width="300px"
            >
            </el-table-column>
            <el-table-column
              prop="submitMsg"
              label="审核意见"
              :show-overflow-tooltip="true"
              min-width="100px"
            >
            </el-table-column>
          </el-table>
        </el-card>
      </div>

      <div
        class="box"
        v-if="flowInfo.currStatus != 'ABORT'"
      >
        <el-card class="box-card horizontal-timeline">
          <div class="title">业务流程图</div>
          <el-steps
            v-if="flowInfo && flowInfo.templateSnapshot"
            :active="currNodeId"
            align-center
            finish-status="success"
          >
            <el-step
              v-for="(item, index) in flowInfo.templateSnapshot.nodes"
              :key="index"
              :title="item.nodeName"
            ></el-step>
          </el-steps>
          <!-- <el-timeline>
            <el-timeline-item
              v-for="(item, index) in flowInfo.templateSnapshot.nodes"
              :key="index"
              placement="top"
            >
              {{ item.nodeName }}
            </el-timeline-item>
          </el-timeline> -->
        </el-card>
      </div>
    </div>
  </div>
</template>

<script>
import FormScore from './modules/FormScore'
import FormApproval from './modules/FormApproval'
import FormContract from './modules/FormContract'
import FormLending from './modules/FormLending'
import FormAccess from './modules/FormAccess'
import FormGuarantee from './modules/FormGuarantee'
import { publish, saveAsDraft, getFlowLog, getFlowByNo, getNodeUsers, approval, getAvailableOption } from '@/api/processManage/approveForms'
export default {
  components: {
    FormScore, FormApproval, FormContract, FormLending, FormAccess, FormGuarantee
  },
  data() {
    return {
      templateInfo: {},
      currentFormComponent: '',
      ruleForm: {
        targetUserName: '',
        approvalMsg: '',
        action: 'TO_NEXT'
      },
      rules: {
        approvalMsg: [
          { required: true, message: '请输入审批意见', trigger: 'change' }
        ],
        action: [
          { required: true, message: '请选择审批处理', trigger: 'blur' }
        ],
        targetUserName: [
          { required: true, message: '请选择下一节点审批人', trigger: 'change' }
        ],
      },
      tableData: [],
      timeline: [
        { content: '发起' },
        { content: '风控审核' },
        { content: '总经理审核' },
        { content: '法务审核' },
        { content: '财务审核' }
      ],

      templateId: '',
      templateName: '',
      templateType: '',

      paramsData: {},
      doc: {},
      flowInfo: {
        currStatus: '',
        templateSnapshot: {
          nodes: [{ nodeName: '发起' }]
        }
      },

      flowLogList: [],
      approveList: [],
      options: {
        enabledEditDoc: false,
        docPermission: {}
      },
      lastNode: null,
      currNodeId: 0,
      routerShow: false
    }
  },
  created() {
    this.routerShow = false
    let procedure = {}
    if (typeof this.$store.state.user.procedure === 'string') {
      procedure = JSON.parse(this.$store.state.user.procedure)
    } else {
      procedure = JSON.parse(JSON.stringify(this.$store.state.user.procedure))
    }

    this.templateName = procedure.templateName
    this.templateId = procedure.templateId
    this.templateType = procedure.templateType
    this.paramsData = procedure.paramsData

    switch (procedure.templateName) {
      case '评分授信':
        this.currentFormComponent = 'FormScore'
        break;
      case '立项申请':
        this.currentFormComponent = 'FormApproval'
        break;
      case '合同制定':
        this.currentFormComponent = 'FormContract'
        break;
      case '放款申请':
        this.currentFormComponent = 'FormLending'
        break;
      case '客户准入':
        this.currentFormComponent = 'FormAccess'
        break;
      case '客户担保':
        this.currentFormComponent = 'FormGuarantee'
        break;

    }
    if (['发起'].includes(procedure.templateType)) {
      const storedFormDoc = localStorage.getItem("formDoc");
      if (storedFormDoc != '{}') {
        setTimeout(() => {
          this.doc = typeof storedFormDoc === 'string' ? JSON.parse(storedFormDoc) : storedFormDoc
        }, 100)
      }
    }

    this.handleGetAvailableOption()
    if (['草稿', '审批', '查看'].includes(procedure.templateType)) {
      this.handleGetFlowByNo()
      this.handleGetFlowLog()
    }
  },
  mounted() { },
  methods: {
    // 获取流程可操作性
    handleGetAvailableOption() {
      getAvailableOption({
        flowNo: this.paramsData.flowNo,
        templateId: this.templateId
      }).then(res => {
        this.options = res.data
      })
    },
    async handleGetFlowByNo() {
      await getFlowByNo({
        flowNo: this.paramsData.flowNo
      }).then(res => {
        this.lastNode = res.data.lastNode

        if (['草稿'].includes(this.templateType)) {
          const storedFormDoc = localStorage.getItem("formDoc");
          if (storedFormDoc != '{}') {
            this.doc = typeof storedFormDoc === 'string' ? JSON.parse(storedFormDoc) : storedFormDoc
          } else {
            this.doc = JSON.parse(res.data.currDoc)
          }
        } else {
          this.doc = JSON.parse(res.data.currDoc)
        }

        this.flowInfo = res.data
        const templateSnapshot = JSON.parse(this.flowInfo.templateSnapshot)
        this.flowInfo.templateSnapshot = templateSnapshot
        const nodes = JSON.parse(templateSnapshot.nodes)
        nodes.unshift({ nodeName: '发起' })
        nodes.push({ nodeName: '结束' })
        this.flowInfo.templateSnapshot.nodes = nodes

        if (res.data.currNodeId === 'STARTER') {
          this.currNodeId = 0
        } else if (res.data.currNodeId === 'SYSTEM') {
          this.currNodeId = nodes.length
        } else {
          this.currNodeId = Number(res.data.currNodeId)
        }

        if (!this.lastNode) {
          this.handleGetNodeUsers()
        }
      })
    },
    // 获取审批人
    handleGetNodeUsers() {
      getNodeUsers({
        templateId: this.templateId,
        flowNo: this.paramsData.flowNo,
        targetAction: this.ruleForm.action,
        targetNodeId: ''
      }).then(res => {
        this.approveList = res.data
        this.ruleForm.targetUserName = res.data.length ? res.data[0].userName : ''
      })
    },
    // 获取审批历史
    handleGetFlowLog() {
      getFlowLog({
        flowNo: this.paramsData.flowNo
      }).then(res => {
        this.flowLogList = res.data
      })
    },
    handleFormSubmit(row) {
      const methods = row.flag === '1' ? publish : saveAsDraft
      if (methods) {
        methods({
          doc: row,
          flowNo: row.flowNo || '',
          targetUserName: row.targetUserName,
          templateId: this.templateId,
        }).then(res => {
          this.routerShow = true
          this.$router.go(-1);
        })
      }
    },
    // 提交审批
    submitForm(formName) {
      if (typeof this.$refs.component.validate === "function" && !this.$refs.component.validate()) {
        return
      }

      let doc = {}
      doc = this.doc
      if (['审批'].includes(this.templateType)) {
        if (this.templateName === '客户准入') {
          if (this.options.docPermission != null) {
            if (this.options.docPermission.admitRateEdit) {
              this.$refs.component.handleSubmitAdditional()
              if (!this.$refs.component.isFormValid) {
                return false; // 如果子组件校验失败，则直接返回
              }
              const form = this.$refs.component.ruleFormReview;
              doc = {
                ...this.doc,
                ...form
              };
            }
          }
        }
        if (this.templateName === '评分授信') {
          if (this.options.docPermission != null) {
            if (this.options.docPermission.priceEdit) {
              const form = this.$refs.component.ruleForm.creditLimit;
              doc = {
                ...this.doc,
                creditLimit: Number((form * 10000).toFixed(2))
              };
            }
          }
        }
      }
      this.$refs[formName].validate((valid) => {
        if (!valid) return false;
        this.routerShow = true
        if (typeof this.$refs.component.getNewDoc === "function") {
          doc = this.$refs.component.getNewDoc()
        }
        approval({
          templateId: this.templateId,
          flowNo: this.paramsData.flowNo,
          targetNodeId: '',
          doc: doc,
          ...this.ruleForm,
          approvalMsg: this.options.enabledSubmitMsg ? this.ruleForm.approvalMsg : '',
          targetUserName: this.ruleForm.action == 'TO_NEXT' ? this.ruleForm.targetUserName : ''
        }).then(res => {
          this.$modal.msgSuccess('提交成功');
          this.$router.go(-1);
          this.handleGetAvailableOption()
          this.handleGetFlowLog()
        })
      });
    },
    // 撤销 作废
    submitFormOption(option) {
      approval({
        templateId: this.templateId,
        flowNo: this.paramsData.flowNo,
        targetNodeId: '',
        doc: this.doc,
        targetUserName: '',
        approvalMsg: '',
        action: option
      }).then(res => {
        this.routerShow = true
        this.$modal.msgSuccess('提交成功');
        this.$router.go(-1);
        this.handleGetAvailableOption()
        this.handleGetFlowLog()
      })
    },
  },
  beforeRouteLeave(to, from, next) {
    if (['发起', '草稿'].includes(this.templateType)) {
      if (this.routerShow) {
        next();
      } else {
        this.$confirm('数据尚未保存,确定要离开吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$store.state.tagsView.visitedViews = this.$store.state.tagsView.visitedViews.filter(item => item.title != "流程发起")
          localStorage.setItem("formDoc", JSON.stringify(this.$refs.component.ruleForm));
          next();
        }).catch(() => {
          const newView = {
            fullPath: "/processManage/approveForms",
            name: "ApproveForms",
            path: "/processManage/approveForms",
            title: "流程发起"
          };
          if (!this.$store.state.tagsView.visitedViews.some(item => item.title === newView.title)) {
            const index = this.$store.state.tagsView.visitedViews.findIndex(item => item.title === newView.title);
            if (index === -1) {
              this.$store.state.tagsView.visitedViews.push(newView);
            } else {
              this.$store.state.tagsView.visitedViews.splice(index, 1, newView);
            }
          }
          next(false);
        });
      }
    } else {
      next();
    }
  }
};
</script>

<style lang="scss" scoped>
.box {
  margin-bottom: 20px;
  .title {
    margin-bottom: 10px;
    font-size: 14px;
    font-weight: bold;
  }
  .el-timeline {
    display: flex;
    flex-direction: row;
    align-items: center;
  }
  .el-timeline-item {
    flex: 1;
    display: flex;
    flex-direction: column;
    align-items: center;
    :deep(.el-timeline-item__tail) {
      position: absolute;
      left: 0px;
      top: 4px;
      width: 100%;
      border-left: none;
      border-top: 2px solid #dfe4ed;
    }
    :deep(.el-timeline-item__wrapper) {
      position: relative;
      padding-left: 28px;
      top: 20px;
      left: -50%;
    }
  }
}
</style>
